var html_1='<p class="m-time">${time}</p>'+
'<div class="m-list clearfix">'+
'<div class="r-head"><img src="${src}" alt=""></div>'+
'<div class="r-con">'+
    '<div class="right"></div>'+
    '<p class="i18n" data-i18n="text">${cont}</p>'+
'</div>'+
'</div>';
var html_2='<p class="m-time">${time}</p>'+
'<div class="m-list clearfix">'+
    '<div class="l-head"><img src="${src}" alt=""></div>'+
    '<div class="l-con">'+
        '<div class="left"></div>'+
        '<p>${cont}</p>'+
    '</div>'+
'</div>';
var html_img ='<img class="up_pictures" src="img/userImg/${img_pho}"/>';
var other_id=getUrlParam();
var from =other_id.from;
var to=other_id.to;
var ip="localhost";
var port=8888;
var socket;
username = from;
var password = 123;
var socket=  new WebSocket("ws:"+ip+":"+port+"?username="+username+"&password="+password);
$(function(){
    $(".main").height($(document).height()-$('.footer').height()*21/10);
    //登录在线修改
    ajax_1();
    //离线消息的调用
    clloat();
    //滚动条最底部
    scrollToBottom();
    //表情的调用
    $('.em').emotion();
    //sockt的使用
    var ip="localhost";
    var port=8888;
    var socket;
    username = from;
    var password = 123;
    // socket =new webSocket("ws://"+ip+":"+port);
    // socket = new WebSocket("ws:"+ip+":"+port+"?username="+other_id.id+"&password=123");
    socket = new WebSocket("ws:"+ip+":"+port+"?username="+username+"&password="+password);
    socket.onopen = function(e){

    };
    console.log("zhehislianjie"+socket.readyState);
    // socket = new WebSocket("ws://://echo.websocket.org");
    socket.onmessage = function(e) {
        var data = e.data;
        console.log(e.data);
        var dataObj = eval("("+data+")");

        if(dataObj.command == 11){//对方页面的消息;

            var chatObj = dataObj.data;
            if(chatObj.msgType=='0') {
                var createTime =getNowFormatDate();
                var content = $.emoDecode(chatObj.content);
                console.log(content);
                var sendHtml = '';
                sendHtml += html_2.replace('${cont}', content).replace('${time}', createTime);
                $('.main').append(sendHtml);
                scrollToBottom();
            }else if(chatObj.msgType=='1'){
                var createTime =getNowFormatDate();
                var  content=html_img.replace('${img_pho}',chatObj.content);
                console.log(content);
                var sendHtml = '';
                sendHtml += html_2.replace('${cont}', content).replace('${time}',createTime);
                $('.main').append(sendHtml);
                scrollToBottom();
            }

        }else if(dataObj.command == 6) {//登陆命令返回状态处理
            COMMAND_LOGIN_RESP(dataObj);
        }else if(dataObj.command == 20 && dataObj.code == 10016) {//处理离线消息;
            var msgFlag = "离线消息";
            COMMAND_GET_MESSAGE_RESP(dataObj, msgFlag);
        }
    }
    //登录成功状态
    function ajax_1(){
        var obj =new Object();
        obj.userid=from;
        console.log('1');
        $.ajax({
            "type": "POST",
            "url":  "/api/user/getOnline",
            //  .html   localhost:8888    /api/user/getOnline
            "data":obj ,
            "dataType": "json",
            "success":function(result){
                console.log(result);
                // var outHtml='';
                // for(var i=0;i<result.length;i++) {
                //     outHtml += html_1.replace('${user_id}', result[i].username);
                // }
                // $('.cont_ulMax').append(outHtml);
            },
            "error": function() {
                console.log('cuowu');

            }
        })
    }
    //返回 退出登录，改成离线
    $(".header-left").click(function () {
        var obj =new Object();
        obj.from=from;
        obj.to=to;
        console.log( obj.from);
        console.log(obj.to);

        $.ajax({
            "type": "POST",
            "url":  "/api/close",
            //  .html   localhost:8888    /api/user/getOnline
            "data":obj ,
            "dataType": "json",
            "success":function(result){
               console.log("已退出");
            },
            "error": function() {
                console.log('cuowu');
            }

        })
    })



    // ajax 获取离线记录
    function clloat(){
        var obj =new Object();
        obj.from=from;
        obj.to=to;
        console.log("获取离线消息");
        $.ajax({
            "type": "POST",
            "url":  "/api/user/getofflinemessages",
            //  .html   localhost:8888    /api/user/getOnline
            "data":obj ,
            "dataType": "json",
            "success":function(result){
                console.log(result);
                var data =result.rs;
                var outHtml='';
                for(var i=0;i<data.length;i++){
                    var content =  $.emoDecode(data[i].content);
                    outHtml += html_2.replace('${cont}',content ).replace('${time}',  data[i].time2);
                }
                $('.main').append(outHtml);
                scrollToBottom();
                //
                //  for(var i=0;i<result.length;i++) {
                //      outHtml += html_1.replace('${user_id}', result[i].username);
                //  }
                //  $('.cont_ulMax').append(outHtml);
            },
            "error": function() {
                console.log('cuowu');
            }
        })
    }
    //获取历史消息
    $('.more_cont').click(function () {
        console.log("历史");
        more_history();
    });

    function  more_history(){
        // api/user/history
        var obj =new Object();
        obj.from=from;
        obj.to=to;
        console.log("dianyong");
        $.ajax({
            "type": "POST",
            "url":  "/api/user/history",
            //  .html   localhost:8888    /api/user/getOnline
            "data":obj ,
            "dataType": "json",
            "success":function(result){
                console.log(result);
                $(".main").html("");
                var data =result.rs;
                var content='';
                for(var i=0;i<data.length;i++){
                    if(data[i].msgType=='0'){
                        content = $.emoDecode(data[i].content);
                    }else if(data[i].msgType=='1'){
                         content=data[i].content;
                    }
                    var outHtml='';
                    if (data[i].from=from) {
                        outHtml = html_1.replace('${cont}', content).replace('${time}',  data[i].time2);
                    }else if(data[i].from=to){
                        outHtml = html_2.replace('${cont}', content).replace('${time}',  data[i].time2);
                    }
                    $('.main').prepend(outHtml);
                }

                scrollToBottom();
                //
                //  for(var i=0;i<result.length;i++) {
                //      outHtml += html_1.replace('${user_id}', result[i].username);
                //  }
                //  $('.cont_ulMax').append(outHtml);
            },
            "error": function() {
                console.log('cuowu');
            }
        })
    }
    //发送图片
    $("#more_photo").change(function(){
        var formData = new FormData();
        formData.append("type", "1");
        formData.append('file', $('#more_photo')[0].files[0]);
        console.log(formData);
        console.log(formData.type);
        console.log( $('#more_photo')[0].files[0]);
        $.ajax({
            "cache": false,
            "processData": false,
            "contentType": false,
            "type": "POST",
            "url":  "/api/aaa",
            "data": formData,
            "success": function (rtnData) {
                var data= JSON.stringify(rtnData);

                var cont=data.replace(/\\/g,'');
               var onedata = JSON.parse(cont);
                var createTime =getNowFormatDate();
                var  content=html_img.replace('${img_pho}',onedata);
                var msg = "{\"from\": \""+from+"\",\"to\": \""+ to+"\",\"cmd\":11,\"chatType\":\"2\",\"msgType\": \"1\",\"createTime\":\""+createTime+"\",\"content\": \""+onedata+"\"}";
                var outHtml='';
                outHtml+=html_1.replace('${cont}',content).replace('${time}', createTime);
                $('.main').append(outHtml);
                socket.send(msg);
                console.log(msg);
                scrollToBottom();
            },
            "error": function () {
                layer.closeAll();
                layer.open({content: "请求失败，请检查网络状况", skin: 'footer'});
            }
        })
    });
    // function readURL(input){
    //     $(".main").height($(document).height()-$('.footer').height()*4.6);
    //     if (input.files && input.files[0]) {
    //         var reader = new FileReader();
    //         reader.onload = function (e) {
    //             var createTime =getNowFormatDate();
    //             var content='<img class="up_pictures" src="'+e.target.result+'"/>';
    //             console.log(content);
    //             var msg = "{\"from\": \""+from+"\",\"to\": \""+ to+"\",\"cmd\":11,\"chatType\":\"2\",\"msgType\": \"1\",\"createTime\":\""+createTime+"\",\"content\": \""+content+"\"}";
    //             var outHtml='';
    //             outHtml+=html_1.replace('${cont}',content).replace('${time}', createTime);
    //             $('.main').append(outHtml);
    //             socket.send(msg);
    //             console.log(msg);
    //            scrollToBottom();
    //         }
    //         reader.readAsDataURL(input.files[0]);
    //     }
        // var createTime =getNowFormatDate();
        // var content='<img src="'+$(this).attr("src")+'"/>'
        // // var msg = "{\"from\": \""+other_id.id+"\",\"to\": \""+ other_id.oid+"\",\"cmd\":25,\"msgType\": \"0\",\"createTime\":\"+createTime+\",\"content\": \""+inputText+"\"}";
        // var msg = "{\"from\": \""+from+"\",\"to\": \""+ to+"\",\"cmd\":11,\"chatType\":\"2\",\"msgType\": \"1\",\"createTime\":\""+createTime+"\",\"content\": \""+$(this).attr("src")+"\"}";
        // var outHtml='';
        // outHtml+=html_1.replace('${cont}',content).replace('${time}', createTime);
        // $('.main').append(outHtml);
        // socket.send(msg);
        // scrollToBottom();
        // console.log($(this).attr("src"));
    // }
    $('#send_up').click(function(){
        if($('#input').html().length!=0){
        var inputText=$('#input').html().replace(/<img id="footer_img" src="[\w]*\/[\w]*\/([0-9]*).[\w]{3}">/g, '[em_$1]');
        var emText=$('#input').html();
        console.log(inputText);
        var createTime =getNowFormatDate();
        // var msg = "{\"from\": \""+other_id.id+"\",\"to\": \""+ other_id.oid+"\",\"cmd\":25,\"msgType\": \"0\",\"createTime\":\"+createTime+\",\"content\": \""+inputText+"\"}";
        var msg = "{\"from\": \""+from+"\",\"to\": \""+ to+"\",\"cmd\":11,\"chatType\":\"2\",\"msgType\": \"0\",\"createTime\":\""+createTime+"\",\"content\": \""+inputText+"\"}";
        //发送msg
        socket.send(msg);
        var chatObj = eval("("+msg+")");
        console.log(chatObj);
        var outHtml='';
        outHtml+=html_1.replace('${cont}',emText).replace('${time}', createTime);
        $('.main').append(outHtml);
        scrollToBottom();
        $('.inp').html('');
        }else{
            console.log("内容为空"+$('#input').html().length);
        }
    })
    function  fali(data){
        console.log(data);
    }
 // $('#input').bind('DOMNodeInserted',function () {
 //     if($('#input').html().length!=0) {
 //             $('#send_up').show();
 //             $('#send_add').hide();
 //     }else if($('#input').html().length==0){
 //         $('#send_up').hide();
 //         $('#send_add').show();
 //     }
 // })
 //   计时时间
    setInterval(function() {
        if($('#input').html().length!=0) {
            $('#send_up').show();
            $('#send_add').hide();
        }else if($('#input').html().length==0){
            $('#send_up').hide();
            $('#send_add').show();
        }
    }, 100);

    // $("#input").focus(function () {
    //     $('#send_up').show();
    //     $('#send_add').hide();
    // })
    // $("#input").blur(function () {
    //     $('#send_add').show();
    //     $('#send_up').hide();
    // })
    $('#send_add').click(function () {
        $(".main").height($(document).height()-$('.footer').height()*4.6);
        scrollToBottom();
        $('.footer').addClass("lastFooter");
        $('#emo').hide();
        $("#add_more").show();
    })
    // $('.more_img').click(function(){
    //     $(".main").height($(document).height()-$('.footer').height()*4.6);
    //     scrollToBottom();
    //     // $('#emo').hide();
    //     // $("#add_more").hide();
    //     // $("#more_photo").show();
    //
    // })
})
function getUrlParam() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}
// 时间
Date.prototype.Format = function (fmt) { //author: wchao
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
   }
//获取当前时间，格式YYYY-MM-DD
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}
//登陆通知处理
function COMMAND_LOGIN_RESP(dataObj){
    if(10007 == dataObj.code){//登陆成功;
        // logDiv.innerHTML+="<font color='green' size='1'>连接成功...</font><br>";
         var userCmd = "{\"cmd\":17,\"type\":\"0\",\"userid\":\""+from+"\"}";
        var msgCmd = "{\"cmd\":19,\"type\":\"0\",\"userId\":\""+from+"\"}";
         // socket.send(userCmd);//获取登录用户信息;
        // socket.send(msgCmd);//获取用户离线消息(好友+群组);
        // scrollToBottom();
    }
}
//处理用户同步+持久化消息
function COMMAND_GET_MESSAGE_RESP(data,msgFlag){
    var msgObj = data.data;
    friendOfflineMessage(msgObj,msgFlag);
    // groupOfflineMessage(msgObj,msgFlag);
}
//好友消息
function friendOfflineMessage(msgObj,msgFlag){
    var friends = msgObj.friends;
    for (var key in friends) {
        var chatDatas = friends[key];
        for(var index in chatDatas){
            var user_id = chatDatas[index].from;
            var createTime = new Date(chatDatas[index].createTime).Format("yyyy/MM/dd HH:mm:ss");
            logDiv.innerHTML+="<font color='	#009ACD' size='1' style='font-weight: bold'>"+user_id+"</font><font color='#DC143C' size='1' style='font-weight: bold'>(好友"+msgFlag+")</font>"+"<font color='#009ACD' size='1' style='font-weight: bold'>"+createTime+"</font><br>";
            logDiv.innerHTML+="<font color='#FFFFFF' size='1'>&nbsp;"+chatDatas[index].content+"</font><br>";
        }
    }
}
function scrollToBottom() {
    var content = $(".main");
    console.log(content.height());
    content.scrollTop(content[0].scrollHeight);
}

